package com.dms.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.common.utils.FileUploadUtils;
import com.dms.modules.user.dto.UserLoginDTO;
import com.dms.modules.user.entity.User;
import com.dms.modules.user.mapper.UserMapper;
import com.dms.modules.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Primary
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private FileUploadUtils fileUploadUtils;

    private static final String AVATAR_UPLOAD_DIR = "uploads/avatars/";
    private static final long MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
    private static final String[] ALLOWED_EXTENSIONS = {"jpg", "jpeg", "png", "gif"};

    @Override
    public User getByUsername(String username) {
        return getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));
    }

    @Override
    public User getByPhone(String phone) {
        return getOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, phone));
    }

    @Override
    public User getByEmail(String email) {
        return getOne(new LambdaQueryWrapper<User>()
                .eq(User::getEmail, email));
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        
        // 检查用户状态
        if (user.getStatus() != 1) {
            log.warn("用户已被禁用：{}", username);
            throw new UsernameNotFoundException("用户已被禁用");
        }
        
        // 确保用户角色是正确的
        if (user.getRoleId() == null) {
            // 如果roleId为空，默认设置为普通用户
            user.setRoleId(3L);
            updateById(user);
        }
        
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User login(UserLoginDTO loginDTO) {
        User user = getByUsername(loginDTO.getUsername());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new BusinessException("密码错误");
        }
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String uploadAvatar(Long userId, MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException("请选择要上传的头像文件");
        }

        try {
            // 使用 FileUploadUtils 上传到 OSS
            String avatarUrl = fileUploadUtils.uploadAvatar(file);
            
            // 更新用户头像URL
            User user = getById(userId);
            if (user == null) {
                throw new BusinessException("用户不存在");
            }
            user.setAvatar(avatarUrl);
            updateById(user);

            return avatarUrl;
        } catch (Exception e) {
            log.error("上传头像失败", e);
            throw new BusinessException("上传头像失败：" + e.getMessage());
        }
    }

    private boolean isAllowedExtension(String extension) {
        for (String allowed : ALLOWED_EXTENSIONS) {
            if (allowed.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean deleteAvatar(Long userId) {
        User user = getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        user.setAvatar(null);
        return updateById(user);
    }

    @Override
    public int checkPasswordStrength(String password) {
        if (password == null || password.length() < 6) {
            return 1; // 弱
        }

        boolean hasLetter = false;
        boolean hasDigit = false;
        boolean hasSpecial = false;

        for (char c : password.toCharArray()) {
            if (Character.isLetter(c)) {
                hasLetter = true;
            } else if (Character.isDigit(c)) {
                hasDigit = true;
            } else {
                hasSpecial = true;
            }
        }

        int strength = 1; // 默认弱
        if (hasLetter && hasDigit) {
            strength = 2; // 中
        }
        if (hasLetter && hasDigit && hasSpecial && password.length() >= 8) {
            strength = 3; // 强
        }

        return strength;
    }

    @Override
    public List<User> getUserListByRoleId(Long roleId) {
        if (roleId == null) {
            return Collections.emptyList();
        }
        
        return this.list(new LambdaQueryWrapper<User>()
                .eq(User::getRoleId, roleId)
                .eq(User::getStatus, 1)  // 只获取正常状态的用户
                .orderByDesc(User::getCreateTime));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserStatus(Long userId, Integer status) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        if (status == null || (status != 0 && status != 1)) {
            throw new BusinessException("状态值无效，只能是0或1");
        }
        
        User user = getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        
        // 更新用户状态
        user.setStatus(status);
        return updateById(user);
    }
} 